<?php
namespace app\api\controller;
use think\Db;
use think\request;
use think\Controller;
use app\common\model\Prt;
use app\common\model\Csv;
class Sy extends Controller
{
	protected function _initialize() {
		header('Access-Control-Allow-Origin:*');
	}
	function get_loginfo(){
		$paylog=db('log_paylog')->where('id',input("log_id"))->find();
		$goods=array();
		$field="goods_name";
		if($paylog['goods_id']){
			$goods=db('agent_goods')->where("id",$paylog['goods_id'])->find();
			$goods['num']=$paylog['goods_num'];
			$goods['price']=$paylog['origin_price'];
		}else if($paylog['order_id']){
			$goods=db('agent_syorder_items')->alias('a')->
			join("agent_goods b","a.goods_id=b.id")->where("order_id",$paylog['order_id'])->field("b.goods_name,a.num,a.price")->select();
		}
		return json(["log"=>$paylog,"goods"=>$goods]);
	}
	//收银员收款二维码
	function emp_code(){
		$code_url="http://".$_SERVER['HTTP_HOST']."/index/pay/qrcode_pay?agent_id=".input("agent_id")."&store_id=".input("store_id")."&clerk_id=".input("clerk_id");
		return json(["url"=>$code_url]);
	}
	function prt(){
		$prt=new Prt();	
		$res=$prt->print_order2(input("order_id"));
		if($res){
			return json(['code'=>200,'msg'=>'打印成功']);
		}else{
			return json(['code'=>400,'msg'=>'打印失败']);
		}
	}
	function prt2(){
		$prt=new Prt();	
		$res=$prt->print_order3(input("log_id"));
		if($res){
			return json(['code'=>200,'msg'=>'打印成功']);
		}else{
			return json(['code'=>400,'msg'=>'打印失败']);
		}
	}
	public function prt_item(){
		$prt=new Prt();	
		$res=$prt->print_items2(input("order_id"));
	}
	//鼓励金判断
	private function do_pay($agent,&$p_score,&$zs_score,&$pay_price,$user_id){
		if($pay_price<1){
			return;
		}
		if($agent['is_score']==1){//开启鼓励金营销
			$p_score=$pay_price*$agent['ad_score']/100;//抵扣积分
			$user=db('info_user')->field("score")->find($user_id);
		    if($p_score&&$user['score']>=$p_score){//用户积分抵扣
				$pay_price=$pay_price-$p_score;//抵扣后订单价格
			}else{//赠送鼓励金
				$p_score=0;
				$zs_score=$pay_price*$agent['zs_score']/100;//赠送积分
				if($agent['score']<$zs_score){
					header("Content-type: text/html; charset=utf-8"); 
					echo '商家鼓励金不足！！！';exit;
				}
			}			
		}
	}
	//商品收银鼓励金判断
	private function do_pay1($agent,&$p_score,&$zs_score,&$pay_price,$user_id){
		if($pay_price<1){//小于1块不送
			$zs_score=0;
			$p_score=0;
			return;
		}
		if($agent['is_score']==1){//开启鼓励金营销
			$user=db('info_user')->field("score")->find($user_id);
		    if($user['score']>=0){//用户积分抵扣
		    	if($p_score&&$user['score']>=$p_score){
		    	 	$pay_price=$pay_price-$p_score;//抵扣后订单价格
		    	}else{
		    		$pay_price=$pay_price-$user['score'];
					$p_score=$user['score'];
		    	}
				$zs_score=0;
			}else{//赠送鼓励金
				$p_score=0;
				if($agent['score']<$zs_score){
					header("Content-type: text/html; charset=utf-8"); 
					echo '商家鼓励金不足！！！';exit;
				}
			}			
		}else{
			$zs_score=0;
			$p_score=0;
			return;
		}
	}
	//分店统计报表
	public function chain_report(){
		$type=input("type");
		if($type==2){//按周
			$time="DATE_FORMAT(add_time,'%Y-%v')";
		}else if($type==3){//按月
			$time="DATE_FORMAT(add_time,'%Y-%m')";
		}else if($type==1){//按日
			$time="DATE_FORMAT(add_time,'%Y-%m-%d')";
		}
		if(input("page")){
			$page=input("page");
		}else{
			$page=1;
		}
		$pg=$page-1;
		$begin=$pg*7;
		$where['state']=2;
		$where['chain_id']=input("chain_id");
		$field=" $time as days,count(id) as nums,sum(member_score) as score,sum(balance) as balance";
		$list=db("log_paylog")->where($where)->field($field)->group($time."desc")->limit($begin,10)->select();
		$where['uid']=["neq",''];//扫码
		//扫码
		$list1=db("log_paylog")->where($where)->field($field)->group($time."desc")->limit($begin,10)->select();
		$where['uid']='';
		//记账
		$list2=db("log_paylog")->where($where)->field($field)->group($time."desc")->limit($begin,10)->select();
		
		$list_sy=[];//营业额
		if($list){
			foreach($list as $k=>$v){
				$list_sy[$v['days']]=$v;
			}				
		}
		
		$list_sm=[];//扫码
		if($list1){
			foreach($list1 as $k=>$v){
				$list_sm[$v['days']]=$v;
			}				
		}
		$list_jz=[];//记账
		if($list2){
			foreach($list2 as $k=>$v){
				$list_jz[$v['days']]=$v;
			}				
		}
		$res=[];
		$data=[];
		foreach($list_sy as $k=>$v){

			$res["time"]=$v['days'];
			$res['result']['nums']=$v['nums'];
			$res['result']['total_money']=$v['balance'];
			$res['result']['total_score']=$v['score'];
			
			$res['result']['sm_nums']=isset($list_sm[$v['days']])?$list_sm[$v['days']]['nums']:0;
			$res['result']['sm_money']=isset($list_sm[$v['days']])?$list_sm[$v['days']]['balance']:0;
			$res['result']['sm_score']=isset($list_sm[$v['days']])?$list_sm[$v['days']]['score']:0;
			
			$res['result']['jz_nums']=isset($list_jz[$v['days']])?$list_jz[$v['days']]['nums']:0;
			$res['result']['jz_money']=isset($list_jz[$v['days']])?$list_jz[$v['days']]['balance']:0;
			$res['result']['jz_score']=isset($list_jz[$v['days']])?$list_jz[$v['days']]['score']:0;
			$data[]=$res;		
		}
		return json(["data"=>$data]);
	}
	//开启或关闭鼓励金营销
	public function set_score(){
		$res=db('info_agent')->where('id',input("agent_id"))->update(["is_score"=>input("state")]);
		if($res){
			return json(['code'=>200,'操作成功']);
		}else{
			return json(['code'=>400,'操作失败']);
		}
	}
//查找商家收银
	public function get_agentinfo(){
		$version="1.04";
		$message="软件更新了一下功能<br/>1.修正部分数据bug<br/>";
		$agent=db('info_agent')->field("is_score,score")->find(input("agent_id"));
		$where['state']=2;
		$where['agent_id']=input('agent_id');
		$list=db("log_paylog")->where($where)->whereTime("add_time","today")->field("balance,pay_type,sy_type,score,agent_score")->select();
		$data['jz_total']=0;
		$data['jz_score']=0;
		$data['sm_total']=0;
		$data['sm_score']=0;
		if($list){
			foreach($list as $k){
				if($k['pay_type']==1){
					$data['jz_total'] +=$k['balance'];
				}else{
					$data['sm_total'] +=$k['balance'];
				}
				if($k['agent_score']>0){
					$data['sm_score'] +=$k['agent_score'];
				}else{
					$data['jz_score'] +=$k['agent_score'];
				}
				
			}
		}
		$data["agent"]=$agent;
		return json(["data"=>$data,"version"=>$version,"message"=>$message]);
		
	}
	
	//商家会员
	public function get_members(){
		$agent=db('info_agent')->field("user_id")->find(input("agent_id"));
		$where['level']=$agent['user_id'];
		if(input("mobile")){
			$where['mobile']=["like","%".input("mobile")."%"];
		}
		if(input("start_time")&&input("end_time")){
			$where['add_time']=['between',[input('start_time'),input('end_time')]];
		}else{
			if(input("start_time")){
				$where['add_time']=[">=",input('start_time')];
			}
			if(input("end_time")){
				$where['add_time']=["<=",input('end_time')];
			}
		}
		if(input("page")){
			$page=input("page");
		}else{
			$page=1;
		}
		$pg=$page-1;
		$begin=$pg*7;
		$count=db('info_user')->where($where)->count();
		$field="user_name,mobile,add_time,sex,score";
		$list=db('info_user')->where($where)->field($field)->limit($begin,7)->select();
		return json(["list"=>$list,"count"=>$count]);
	}
	//导出报表
	public function export(){
		$ex=new Csv();
		$str ="订单号,消费金额,鼓励金,交易时间,操作员,状态"."\n";
		$where['chain_id']=input('chain_id');
		$where['state']=2;
		if(input("start_time")){
			$where['add_time']=[">=",input('start_time')];
		}
		if(input("end_time")){
			$where['add_time']=["<=",input('end_time')];
		}
		$field="order_sn,balance,score,add_time,clerk_id,state";
		$list=db('log_paylog')->where($where)->select();
		foreach($list as $k=>$v){
			if($v['state']==2){
				$list[$k]['state']='完成';
			}else{
				$list[$k]['state']='未完成';
			}
		}
		$ex->dc($str,$field,$list,'收银记录.csv');
		exit;	
	}
	//收银报表
	public function get_reports(){
		$where['agent_id']=input('agent_id');
		if(input("chain_id")){
			$where['chain_id']=input("chain_id");
		}
		$where['state']=2;
		if(input("sn")){
			$where['order_sn']=["like","%".input("sn")."%"];
		}
		if(input("start_time")&&input("end_time")){
			$where['add_time']=['between',[input('start_time'),input('end_time')]];
		}else{
			if(input("start_time")){
				$where['add_time']=[">=",input('start_time')];
			}
			if(input("end_time")){
				$where['add_time']=["<=",input('end_time')];
			}
		}
		
		if(input("page")){
			$page=input("page");
		}else{
			$page=1;
		}
		$pg=$page-1;
		$begin=$pg*7;
		$count=db('log_paylog')->where($where)->count();
		$list=db('log_paylog')->where($where)->limit($begin,7)->order("add_time desc")->select();
		return json(["list"=>$list,"count"=>$count]);
	}
	//查找商品
	public function get_goods(){
		$where="goods_state=2 and stock >0 and agent_id=".input("agent_id");
		
		if(input("name")){
			//$where['goods_name']=["like","%".input('name')."%"];
			$where.=" and pinyin(goods_name) like '%".input('name')."%'";
		}
		$field="id,thumb,unit,goods_no,goods_name,sale_price,zs_price,dk_price";
		$sql ="select $field from agent_goods where $where ";
		//$goods=db("agent_goods")->field($field)->where($where)->select();
		$goods=DB::query($sql);
		return json(["goods"=>$goods]);
		
	}
	//扫码商品
	public function get_gooods(){
		$where['goods_state']=2;
		$where['stock']=['>',0];
		$no=input("no");
		$total_price=0;
		$where['agent_id']=input("agent_id");
		if(input("chain_id")){
		 	$where['chainstore_id']=['in',[0,input('chain_id')]];
		}
		$where['goods_no']=$no;
		$field="id,unit,goods_no,goods_name,sale_price,zs_price,dk_price";
		$good=db("agent_goods")->field($field)->where($where)->find();
		if(strlen($no)==13){
			if(!$good){
				$no=substr($no, 1,6);
				$total_price=substr(input("no"), 7,5);
				$where['goods_no']=trim($no);		
				$good=db("agent_goods")->where($where)->find();
			}
		}
		if($good){
			$good['sale_price']=floatval($good['sale_price']);
			$good['total_price']=$total_price?floatval($total_price)/100:floatval($good['sale_price']);
			$good['nums']=number_format($good['total_price']/$good['sale_price'],2);
		}
		return json(["good"=>$good]);
	}
	//商品收银
	public function goods_sk(){
		 $where['goods_state']=2;
		 $where['agent_id']=input("agent_id");
		 $where['stock']=['>',0];
		 if(input("chain_id")){
		 	$where['chainstore_id']=['in',[0,input('chain_id')]];
		}
		 $field="id,trade_id,thumb,goods_name,agent_id,0 as num, trade_id,sale_price,original_price,zs_price,dk_price";
	 	 $goods=db("agent_goods")->where($where)->field($field)->select();
		 //$type=$this->getTypes($store_id);
		 $type=db('agent_type')->where("agent_id",input("agent_id"))->select();
		 $type1=array();
		 $res=array();
		 foreach($type as $k=>$v){
				$type1[$v['id']]=$v;
		 }
		 foreach($goods as $k=>$v){
		 	$res[$v['trade_id']][]=$v;
		 }
		 $data['type']=$type;
		 return json(['res'=>$res,'type'=>$type1]);
	 }
	//修改房台订单
	public function cg_order(){
		Db::startTrans();
		$order_id=input("order_id");
		$type=input('type');//1增加2减少
		$item_id=input("item_id");
		$price=input('price');
		$dk_price=input('dk_price');
		$zs_price=input('zs_price');
		if($type==1){
			$up['total_price']=["exp","total_price+".$price];
			$up['need_score']=['exp','need_score+'.$dk_price];
			$up['give_score']=['exp','give_score+'.$zs_price];
			$item_up['num']=['exp','num+1'];
		}else{
			$up['total_price']=["exp","total_price-".$price];
			$up['need_score']=['exp','need_score-'.$dk_price];
			$up['give_score']=['exp','give_score-'.$zs_price];
			$item_up['num']=['exp','num-1'];
		}
		
		$res=db("agent_syorder")->where('id',$order_id)->update($up);
		$result=true;
		if(!$res){
			$result=false;
		}
		$res=db('agent_syorder_items')->where('id',$item_id)->update($item_up);
		if(!$res){
			$result=false;
		}
		if(!$result){
			Db::rollback();
			return json(["code"=>400,'msg'=>'修改失败']);
		}else{
			Db::commit();
			return json(["code"=>200,'msg'=>'修改成功']);
		}
	}
	//房台下单
	public function add_horder(){
		$agent_id=input("agent_id");
		$status=input("status");
		$house_id=input("house_id");
		$emp_id=input("emp_id");
		$where['house_id']=$house_id;
		$where['status']=1;
		$goods=input('post.')['data'];
		$items=array();
		$add_time=now_time();
		$chain_id=input("chain_id");
		$where['chain_id']=$chain_id;
		$order=db("agent_syorder")->where($where)->field("sn,id,status,need_score,give_score,total_price")->find();
		$total_zs=0;
		$total_dk=0;
		foreach($goods as $i){
			$total_zs+=$i['zs']*$i['num'];
			$total_dk+=$i['dk']*$i['num'];
		}
		$sn=$order?$order['sn']:order_create_no();
		if($order){
			$total_zs=$order['give_score']+$total_zs;
			$total_dk=$order['need_score']+$total_dk;
		}
		$price=$order?$order['total_price']+input("price"):input('price');
		$res=$this->add_syorder($sn,$agent_id,1,$total_dk,$total_zs,$price,0,0
		,$emp_id,$chain_id,1,1,5,$house_id);
		foreach($goods as $i){
			$items[]=array('type_id'=>$i['type_id'],'update_time'=>now_time(),"dk_price"=>$i['dk'],"zs_price"=>$i['zs'],"order_id"=>$res,"goods_id"=>$i['id'],"price"=>$i['price'],"num"=>$i['num'],"agent_id"=>$agent_id,"name"=>$i['name']);
		}
		$res2=db('agent_syorder_items')->insertAll($items);
		if($res2){
			if($status!=3){
				$up['status']=3;
			}
			$up['nums']=input("people_nums");
			if(input("memo")){
				$up['memo']=input('memo');
			}
			db('agent_house')->where("id",$house_id)->update($up);
			$prt=new Prt();	
			//$prt->print_items($res);
			$items=db("agent_syorder_items")->where("order_id",$res)->select();
			return json(['code'=>200,'msg'=>"下单成功 ","order_id"=>$res,"items"=>$items,'total_price'=>$price]);
		}else{
			return json(['code'=>400,'msg'=>"下单失败 "]);
		}
	}
	/**
	 * 开关启房台
	 */
	public function update_house(){
		$house_id=input('house_id');
		$res=db("agent_house")->where("id",$house_id)->update(["status"=>input("status"),"add_time"=>now_time()]);
		if($res){
			if(input("status")==1){//关台后关闭订单
				$where['house_id']=$house_id;
				$where['status']=1;
			    db("agent_syorder")->where($where)->update(["status"=>3]);
			}elseif(input('status')==4){//已结
				$where['house_id']=$house_id;
				$where['status']=2;
			    db("agent_syorder")->where($where)->update(["status"=>5]);
			}
			return json(['code'=>200,'msg'=>'操作成功','add_time'=>substr(now_time(),10,18)]);
		}
		return json(['code'=>408,'msg'=>'操作失败']);
	}
	/**
	 * 获取房台信息
	 */
	public function get_houseinfo(){
		$house=db("agent_house")->field("name,status,add_time")->find(input("house_id"));
		if($house['status']==1){
			return json(['code'=>404,'msg'=>'未开台','house'=>$house]);
		}
		$house['add_time']=substr($house['add_time'], 11,18);
		$where['house_id']=input("house_id");
		//已结账未还未关台
		if($house['status']==4){
			$where['status']=2;			
		}else{//未结账
			$where['status']=1;
		}
		$where['agent_id']=input("agent_id");
		$field="total_price,id,add_time";
		$order=db("agent_syorder")->where($where)->field($field)->find();
		if($order){
			$list=db("agent_syorder_items")->where("order_id",$order['id'])->order("update_time asc")->select();
			$order['item']=$list;
			return json(['code'=>200,'data'=>$order,'house'=>$house]);
		}
		return json(['code'=>406,'msg'=>'未点单','house'=>$house]);
	}
	//根据类型获取房台
	public function get_housesbt(){
		$where['agent_id']=input("agent_id");
		$where['state']=1;
		if(input("type_id")){
			$where['type_id']=input("type_id");
		}
	 	$houses=db("agent_house")->where($where)->select();
		return json(['houses'=>$houses]);
	}
	// 房台删除商品
	public function del_gd(){
		Db::startTrans();
		$num=input("num");
		$price=input("price")*$num;
		$dk_price=input("dk_price")*$num;
		$zs_price=input("zs_price")*$num;
		$order_id=input("order_id");
		//修改订单表数据
		$sql="update agent_syorder set total_price=total_price-$price";
		$sql.=",give_score=give_score-$zs_price,need_score=need_score-$dk_price";
		$sql.=" where id=:id ";
		$result=Db::execute($sql,["id"=>$order_id]);
		if($result){
			//删除订单字表商品数据
			$res=db("agent_syorder_items")->delete(input("item_id"));
			if($res){
				Db::commit();
				return json(['code'=>200,'msg'=>'操作成功']);
			}else{
				Db::rollback();
				return json(['code'=>400,'msg'=>'操作失败']);
			}
		}else{
			return json(['code'=>400,'msg'=>'操作失败']);
		    Db::rollback();
		}
	}
	//房台收银
	public function get_houses(){
		 $where['agent_id']=input("agent_id");
		 $where['state']=1;
	 	 $houses=db("agent_house")->where($where)->select();
		 //$type=$this->getTypes($store_id);
		 $type=db('agent_housetype')->where("agent_id",input("agent_id"))->select();
		 $type1=array();
		 $res=array();
		 foreach($type as $k=>$v){
				$type1[$v['id']]=$v;
		 }
		 foreach($houses as $k=>$v){
		 	$res[$v['type_id']][]=$v;
		 }
		 $data['type']=$type;
		 return json(['res'=>$res,'type'=>$type1]);
	 }
	//android商品收银
	public function app_goods_sk(){
		 $field="id,goods_name,agent_id,0 as num, trade_id,sale_price,original_price,zs_price,dk_price";
		 $where['goods_state']=2;
		 $where['stock']=['>',0];
		 if(input("chain_id")){
		 	$where['chainstore_id']=['in',[0,input('chain_id')]];
		 }
		 $where['agent_id']=input("agent_id");
		 if(input("trade_id")){
		 	$where['trade_id']=input("trade_id");
		 }
	 	 $goods=db("agent_goods")->where($where)->field($field)->select();
		 return json(['goods'=>$goods]);
	 }
	public function goods_tp(){
		 $type=db('agent_type')->where("agent_id",input("agent_id"))->field("id,type_name,agent_id")->select();
		return json(['type'=>$type]);
	}
	//添加收银订单
	private function add_syorder($sn,$agent_id,$pay_type,$p_score,$zs_score,
	$price,$pay_price,$user_id,$emp_id,$chain_id,$oem_id,$status,$type,$house_id=0){
			$order=db("agent_syorder")->where('sn',$sn)->find();
				$data['sn']=$sn;
				$data['agent_id']=$agent_id;
				$data['user_id']=$user_id;
				$data['emp_id']=$emp_id;
				$data['chain_id']=$chain_id;
				$data['oem_id']=$oem_id;
				$data['total_price']=$price;
				$data['pay_type']=$pay_type;
				$data['pay_price']=$pay_price;
				$data['add_time']=now_time();
				$data['need_score']=$p_score;
				$data['give_score']=$zs_score;
				$data['status']=$status;
				$data['type']=$type;
				$data['house_id']=$house_id;
				if($order){
					$res=db('agent_syorder')->where('sn',$sn)->update($data);
					if(!$res){
						header("Content-type: text/html; charset=utf-8"); 
						echo "订单创建失败";exit;
					}else{
						if(!$house_id){
							$items=db("agent_syorder_items")->where("order_id",$order['id'])->select();
							if($items){
								foreach($items as $i){
									//如果是赠送
									$gd=db("agent_goods")->field("zs_price,dk_price")->where("id",$i['goods_id'])->find();
									if($p_score>0){
										db('agent_syorder_items')->where("id",$i['id'])->update(["dk_price"=>$gd['dk_price']]);
									}elseif($zs_score>0){
										db('agent_syorder_items')->where("id",$i['id'])->update(["zs_price"=>$gd['zs_price']]);
									}
								}
							}
						}
						return $order['id'];
					}
				}else{
					$res=db('agent_syorder')->insertGetId($data);
					if(!$res){
						header("Content-type: text/html; charset=utf-8"); 
						echo "订单创建失败";exit;
					}else{
						return $res;
					}	
				}
				
	}
	//完成检查订单
	function ck_order(){
		$field="status";
		$order=db('agent_syorder')->where("id",input("order_id"))->field($field)->find();
		if(!$order){
			return json(['code'=>400,'msg'=>'订单不存在']);
		}
		if($order['status']!=2){
			return json(['code'=>406,'msg'=>'订单未支付完成']);
		}else{
			return json(['code'=>200,'msg'=>'支付完成']);
		}
	}
	//用户扫码收银
	function sk(){
		$order=db('agent_syorder')->find(input("oid"));
		if($order&&$order['status']==2){
			header("Content-type: text/html; charset=utf-8"); 
			echo "请勿重复支付";exit;
		}elseif(!$order){
			header("Content-type: text/html; charset=utf-8"); 
			echo "无效订单";exit;
		}
		$p_score=$order['need_score'];//抵扣鼓励金
		$zs_score=$order['give_score'];//赠送鼓励金
		$price=$order['total_price'];//订单价
		$pay_price=$price;//实际支付价格
		$type=get_brower_type();//判断是微信还是支付宝打开
		$agent=db('info_agent')->field("is_state,salesman_id,agency_id1,agency_id2,ali_sellid,ali_token,id,is_score,ad_score,zs_score,score,cb_no,cb_clerk,cb_miyao,wx_way,ali_way,user_id,agency_id1,agency_id2,oem_id")->find($order['agent_id']);
		$redirect=config('API_DOMAIN')."api/sy/sk?oid=".$order['id']."&type=".input("type");
		//echo $redirect;exit;
		if($type==1){
			$auth_code=input("auth_code");
			$url ='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='.config('alipay_appid').'&scope=auth_base&redirect_uri='.urlencode($redirect);
		}else{
			$auth_code=input("code");
			$url ='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wxpay_appid').'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_base&state=STATE%23wechat_redirect&connect_redirect=1#wechat_redirect';
		}
		if(!$auth_code){
			Header("Location: $url");
			exit;
		}else{
			if($type==1){//支付宝openid
				$field="alipay_id";
				$pay_type=3;
				$openid=user_ali_id($auth_code);
				
			}elseif($type==2){//微信openid
				$field="openid";
				$pay_type=2;
				if(session('cut_auth_code') != $auth_code){
					session('cut_auth_code',$auth_code);
					$openid=user_wx_id($auth_code);
				}else{
					Header("Location: $url");
					exit;
				}
			}	
			if($openid){
				$w_u[$field]=$openid;
				$w_u['oem_id']=$agent['oem_id'];
				$user=db('info_user')->where($w_u)->find();
				if(!$user){
					$data[$field]			= $openid;
					$data['level']			= $agent['user_id'];
					$data['agency_id1']		= $agent['agency_id1'];
					$data['agency_id2']		= $agent['agency_id2'];
					$data['oem_id']			= $agent['oem_id'];
					$data['salesman_id']	= $agent['salesman_id'];
					$data['tj_agent']		= $agent['id'];
					$data['add_time']		= now_time();
					$user_id=Db::name('info_user')->insertGetId($data);
				}else{
					$user_id=$user['id'];
				}			
			}
		}
		if($order['type']==3||$order['type']==2||$order['type']==5){//3商品收银5房台
			$this->do_pay1($agent,$p_score,$zs_score,$pay_price,$user_id);			
		}else{
			$this->do_pay($agent,$p_score,$zs_score,$pay_price,$user_id);
		}
		$house_id=0;
		if($order['type']==5){
			$house_id=$order['house_id'];
		}
		Db::startTrans();
		$res=$this->add_syorder($order['sn'],$agent["id"],$pay_type,$p_score,$zs_score,$price,$pay_price,$user_id
		,$order['emp_id'],$order['chain_id'],$order['oem_id'],1,$order['type'],$order['house_id']);
		if($res){
			$log_res=$this->add_log($agent['agency_id1'],$agent['agency_id2'],$user_id,$res,$order['agent_id'],$order['chain_id'],$order['emp_id'],$order['sn'],$pay_type,1,$price,
			$pay_price,$order['oem_id'],input("type"),$house_id);
			if(!$log_res){
				 Db::rollback();
			}else{
				Db::commit();
			}
		}else{
			 Db::rollback();
		}
		
		if($pay_price==0){//纯积分
			header("Content-type: text/html; charset=utf-8"); 
			echo '支付成功';exit;
		}
		if($type==1){//支付宝
	        if($agent&&$agent['is_state']==1){
        		$url=pay_code($agent['cb_no'],$agent['cb_miyao'],$agent['cb_clerk'],round($pay_price,2),1,$order['sn'],'');
				Header("Location: $url");
					exit;
        	}else{
        		header("Content-type: text/html; charset=utf-8"); 
        		echo '支付失败';exit;
        	}
		}elseif ( $type==2 ) {//微信扫码
				if($agent&&$agent['is_state']==1){
        			$url=pay_code($agent['cb_no'],$agent['cb_miyao'],$agent['cb_clerk'],round($pay_price,2),2,$order['sn'],'');
					Header("Location: $url");
					exit;
	        	}else{
	        		header("Content-type: text/html; charset=utf-8"); 
	        		echo '支付失败';exit;
	        	}
		}    
	
	}
	//获取二维码收款信息生成订单
	function get_sk(){
		$agent_id=input('agent_id');
		$price=input("price");
		$agent=db('info_agent')->field("score,is_score,zs_score,ad_score")->find($agent_id);
		$zs =$agent['zs_score'] * $price * 0.01;
		$dk =$agent['ad_score'] * $price * 0.01;
			
		$emp_id=input("emp_id");
		$chain_id=input('chain_id');
		$oem_id=input('oem_id');
		$sn=order_create_no();
		$sy_type=input("type");
		$params=input("");
		$res=$this->add_syorder($sn,$agent_id,1,$dk,$zs,$price,0,0
		,$emp_id,$chain_id,$oem_id,1,$sy_type);
		$url=config("API_DOMAIN")."api/sy/sk?oid=$res&type=".input("type");
		$qrcode= 'http://www.vshop88.net/code/code.php?url='.urlencode($url).'&margin=1&size=10';
		return json(["zs"=>$zs,"dk"=>$dk,"url"=>$qrcode,"app_url"=>$url,"agent"=>$agent,'order_id'=>$res]);
	}
	//房台获取二维码
	function get_housesk(){
		$oid=input("order_id");
		$url=config("API_DOMAIN")."api/sy/sk?oid=$oid&type=4";
		$qrcode= 'http://www.vshop88.net/code/code.php?url='.urlencode($url).'&margin=1&size=10';
		$order=db("agent_syorder")->where("id",$oid)->field("agent_id,give_score,need_score")->find();
		$agent=db("info_agent")->where("id",input("agent_id"))->field("is_score,score")->find();
		return json(["zs"=>$order['give_score'],"dk"=>$order['need_score'],"url"=>$qrcode,"app_url"=>$url,"agent"=>$agent,'order_id'=>$oid,"total_zs"=>$order['give_score'],"total_dk"=>$order['need_score']]);
	}
	//商品收银获取二维码收款信息生成订单
	function get_goodssk(){
		$agent_id=input('agent_id');
		$agent=db('info_agent')->field("score,is_score,zs_score,ad_score")->find($agent_id);
		$price=input("price");
		$emp_id=input("emp_id");
		$chain_id=input('chain_id');
		$oem_id=input('oem_id');
		$sn=order_create_no();
		$sy_type=input("type");
		$params=input("");
		$goods=$params['goods'];//商品
		$total_zs=0;
		$total_dk=0;
		foreach($goods as $i){
			$total_zs+=$i['zs']*$i['num'];
			$total_dk+=$i['dk']*$i['num'];
		}
		$res=$this->add_syorder($sn,$agent_id,1,$total_dk,$total_zs,$price,0,0
		,$emp_id,$chain_id,$oem_id,1,$sy_type);
		foreach($goods as $i){
			$items[]=array("order_id"=>$res,"goods_id"=>$i['id'],"price"=>$i['price'],"num"=>$i['num'],"agent_id"=>$agent_id,"name"=>$i['name']);
		}
		db('agent_syorder_items')->insertAll($items);
		$url=config("API_DOMAIN")."api/sy/sk?oid=$res&type=$sy_type";
		$qrcode= 'http://www.vshop88.net/code/code.php?url='.urlencode($url).'&margin=1&size=10';
		return json(["zs"=>$total_zs,"dk"=>$total_dk,"url"=>$qrcode,"app_url"=>$url,"agent"=>$agent,'order_id'=>$res,"total_zs"=>$total_zs,"total_dk"=>$total_dk]);
	}
	//app端商品收银
	function get_appgoodssk(){
		$agent_id=input('agent_id');
		$agent=db('info_agent')->field("score,is_score,zs_score,ad_score")->find($agent_id);
		$price=input("price");
		$emp_id=input("emp_id");
		$chain_id=input('chain_id');
		$oem_id=input('oem_id');
		$sn=order_create_no();
		$sy_type=input("type");
		$ids=input('ids');
		//$wg=['id','in',$ids];
		$nums=input("nums");
		$nums=explode(",", $nums);
		$goods=db('agent_goods')->where('id','in',$ids)->field("id,goods_name as name,zs_price,dk_price,sale_price as price")->select();
		$total_zs=0;
		$total_dk=0;
		foreach($goods as $k=>$i){
			$total_zs+=$i['zs_price']*$nums[$k];
			$total_dk+=$i['dk_price']*$nums[$k];
		}
		$res=$this->add_syorder($sn,$agent_id,1,$total_dk,$total_zs,$price,0,0
		,$emp_id,$chain_id,$oem_id,1,3);
		foreach($goods as $key=>$i){
			$items[]=array("order_id"=>$res,"goods_id"=>$i['id'],"price"=>$i['price'],"num"=>$nums[$key],"agent_id"=>$agent_id,"name"=>$i['name']);
			//db("agent_goods")->where('id',$i['id'])->setDec("stock",$nums[$key]);
		}
		db('agent_syorder_items')->insertAll($items);
		$url=config("API_DOMAIN")."api/sy/sk?oid=$res&type=".input("type");
		$qrcode= 'http://www.vshop88.net/code/code.php?url='.urlencode($url).'&margin=1&size=10';
		return json(["url"=>$qrcode,"app_url"=>$url,"agent"=>$agent,'order_id'=>$res,"total_zs"=>$total_zs,"total_dk"=>$total_dk]);
	}
	//校验商品库存
	function check_stock(){
		$good=db("agent_goods")->where("id",input('goods_id'))->find();
		if($good){
			if($good['stock']>input("nums")){
				return json(['code'=>200]);
			}else{
				return json(['code'=>400,'msg'=>'商品库存不足！还剩下'.$good['stock'].'份了']);
			}
		}else{
			return json(['code'=>404,'商品不存在']);
		}
	}
	//快速记账
    public function house_jz(){
    	$order_id=input("order_id");
		$order_items=db("agent_syorder_items")->where("order_id",$order_id)->field("goods_id,num")->select();
		$params=input("");
		if($order_items){
			foreach($order_items as $i){
				$sql="update agent_goods set stock =stock - ".$i['num'].",sales=sales+".$i['num']." where id = ".$i['goods_id'];
				$res=DB::execute($sql);
			}
		}else{
			return json(["code"=>400,'msg'=>'未下单记账失败']); 
		}
		db('agent_syorder')->where("id",$order_id)->update(["status"=>2,'pay_time'=>now_time()]);
		$res=$this->add_log(0,0,0,$res,input("agent_id"),input("chain_id"),input("emp_id"),order_create_no(),1,2,input("price"),
		input("price"),1,4,input('house_id'));
		if($res){
			db('agent_house')->where("id",input("house_id"))->update(['status'=>4,"finish_time"=>now_time()]);
			return json(["code"=>200,'msg'=>'记账成功']);	
		}else{
			return json(["code"=>400,'msg'=>'记账失败']);
		}
	}
	//快速记账
    public function jizhang(){
    	// 启动事务
	    $data['agent_id']=input("agent_id");
		$data['chain_id']=input('chain_id');
		$data['emp_id']=input("emp_id");
		if(!input("agent_id")||!input('chain_id')||!input('emp_id')){
			return json(["code"=>404,'msg'=>'记账失败']);		
		}
		$data['add_time']=now_time();
		$data['sn']=order_create_no();
		$data['status']=2;
		$data['total_price']=input('price');
		$data['pay_price']=input('price');
		$data['oem_id']=input('oem_id');
		$res=db('agent_syorder')->insertGetId($data);
		$params=input("");
		$goods=isset($params['goods'])?$params['goods']:null;//商品
		if($res){
			if($goods){
				foreach($goods as $i){
					$items[]=array("order_id"=>$res,"goods_id"=>$i['id'],"price"=>$i['price'],"num"=>$i['num'],"agent_id"=>input("agent_id"),"name"=>$i['name']);
					$sql="update agent_goods set stock =stock - ".$i['num'].",sales=sales+".$i['num']." where id = ".$i['id'];
					DB::execute($sql);
				}
				db('agent_syorder_items')->insertAll($items);
			}
			$agent=db('info_agent')->field("agency_id1,agency_id2")->find(input("agent_id"));
			$this->add_log($agent['agency_id1'],$agent['agency_id2'],0,$res,$data['agent_id'],$data['chain_id'],$data['emp_id'],$data['sn'],1,2,$data['total_price'],
			$data['pay_price'],$data['oem_id'],input("type"));
			return json(["code"=>200,'msg'=>'记账成功','order_id'=>$res]);			
		}else{
	    // 提交事务
		return json(["code"=>400,'msg'=>'记账失败','order_id'=>$res]);		
		}
    }
	//添加日志
	function add_log($agency_id1,$agency_id2,$user_id,$order_id,$agent_id,$chain_id,$emp_id,$sn,$pay_type,$state,$total_price,
	$pay_price,$oem_id,$sy_type=1,$house_id=0){
		$log=db("log_paylog")->where('order_sn',$sn)->field("id")->find();
		if($log){
			return true;
		}
		$data['agency_id1']=$agency_id1;
		$data['agency_id2']=$agency_id2;
		$data['uid']=$user_id;
		$data['order_id']=$order_id;
		$data['agent_id']=$agent_id;
		$data['chain_id']=$chain_id;
		$data['clerk_id']=$emp_id;
		$data['order_type']=6;
		$data['order_sn']=$sn;
		$data['pay_type']=$pay_type;
		$data['state']=$state;
		$data['origin_price']=$total_price;
		$data['balance']=$pay_price;
		$data['oem_id']=$oem_id;
		$data['add_time']=now_time();
		$data['sy_type']=$sy_type;
		$data['order_id']=$order_id;
		$data['house_id']=$house_id;
		$res=db('log_paylog')->insert($data);
		return $res;
	}
	//扫用户付款吗付款
	public function zhu_pay(){
		if(input("mem_no")){
			$no= str_replace(' ', '', input("mem_no"));
			$where["replace(no,' ','')"]=$no;
			$user=db("info_user")->where($where)->field("id,score,openid")->find();
			if(!$user){
				return json(["code"=>400,'msg'=>'会员码不存在']);
			}
		}
		$order=db("agent_syorder")->where('id',input("oid"))->find();
		if(!$order){
			return json(["code"=>400,'msg'=>'订单不存在']);
		}
		if($order['status']==2||$order['status']==4){
			return json(["code"=>400,'msg'=>'请勿重复支付']);
		}
		$agent=db("info_agent")->where('id',$order['agent_id'])->field("id,user_id,agent_name,is_score,zs_score,ad_score,cb_miyao,cb_clerk,cb_no")->find();
		$sn=$order['sn'];
		$need_score=0;
		$give_score=0;
		$agent_score=0;
		$pay_price=$order['total_price'];
		Db::startTrans();
		$result=true;
		if($agent['is_score']==1&&input("mem_no")){//开启鼓励金营销
		    if($user['score']>0){//用户积分抵扣
		    	if($order['type']==1){
		    		$need_score=number_format($pay_price*$agent['ad_score']/100,4);//抵扣积分
		    	}else{
		    		$need_score=$order['need_score'];
		    	}
		    	if($user['score']>=$need_score){
		    		$agent_score=$need_score;
		    		$pay_price=$pay_price-$need_score;//抵扣后订单价格
		    	}else{
		    		$agent_score=$user['score'];
		    		$pay_price=$pay_price-$user['score'];//抵扣后订单价格
		    	}
		    	//减去用户鼓励金
				$rest2 = db('info_user')->where('id', $user['id'])->setDec('score', $agent_score);
				if(!$rest2) $result = false;
				$rest2 =user_score_change($user['id'],6,-$agent_score,"线下消费抵扣鼓励金");
				if(!$rest2) $result = false;
				//增加商家鼓励金
				$rest2 = db('info_agent')->where('id', $agent['id'])->setInc('score', $agent_score);
				if(!$rest2) $result = false;
				$rest2 =agent_score_change($agent['id'],7,$order['chain_id'],$order['emp_id'],$agent_score,'线下收银回收鼓励金');
				if(!$rest2) $result = false;
			}else{//赠送鼓励金
				if($order['type']==1){
		    		$give_score=number_format($pay_price*$agent['zs_score']/100,4);//赠送积分
		    	}else{
		    		$give_score=$order['give_score'];
		    	}
				if($agent_score<$give_score){
					$give_score=0;
				}else{
					$agent_score=-$give_score;
					//增加用户鼓励金
					$rest2 = db('info_user')->where('id', $user['id'])->setInc('score', $give_score);
					if(!$rest2) $result = false;
					$rest2 =user_score_change($user['id'],6,$give_score,"线下消费赠送鼓励金");
					if(!$rest2) $result = false;
					//减去商家鼓励金
					$rest2 = db('info_agent')->where('id', $agent['id'])->setDec('score', $give_score);
					if(!$rest2) $result = false;
					$rest2 =agent_score_change($agent['id'],7,$order['chain_id'],$order['emp_id'],-$give_score,'线下收银赠送鼓励金');
					if(!$rest2) $result = false;
				}			
			}			
		}
		$pay_type=get_bartype(input("mem_card"));
		$log=db("log_paylog")->where('order_sn',$sn)->field("id")->find();
		$res=db("agent_syorder")->where("id",$order['id'])->update(["pay_time"=>now_time(),"status"=>2,"pay_price"=>$pay_price,"need_score"=>$need_score,"give_score"=>$give_score]);
		if(!$res){
			$result=FALSE;
		}
		if($order['type']!=1){
			$items =db('agent_syorder_items')->where('order_id',$order['id'])->field("goods_id,price,sum(num) as num")->group("goods_id")->select();
			foreach($items as $key=>$value){
				$up['stock']=['exp',"stock - {$value['num']}"];
				$up['sales']=['exp',"sales + {$value['num']}"];
				$total_money=$value['num']*$value['price'];
				$up['total_money']=['exp',"total_money + $total_money"];
				//减库存
				db('agent_goods')->where('id', $value['goods_id'])->update($up);
			}
			if($order['type']==5){
				$resh=db('agent_house')->where("id",$order['house_id'])->update(["status"=>4,"finish_time"=>now_time()]);
				if(!$resh) $result = false;
			}
		}
		$res=$this->add_log1($agent_score,$user['id'],$order['id'],$order['agent_id'],$order['chain_id'],$order['emp_id'],$sn,$pay_type,2,$order['total_price'],
		$pay_price,1,1,0);
		if(!$res){
			$result=FALSE;
		}
		if($result){
			$res=bar_pay(input("mem_card"),$agent['cb_no'],$agent['cb_miyao'],$agent['cb_clerk'],$pay_price,1,order_create_no(),'');
			if($res==2){
				Db::commit();
				$user=isset($user)?$user:null;
				$this->set_temp($user,$pay_price,$order['total_price'],$agent_score,$sn,$agent,$order['chain_id']);
				//push_msg($agent['id'],$pay_price);
				return json(["code"=>200,'msg'=>"付款成功",'pay_price'=>$pay_price,'agent_score'=>$agent_score]);
			}else{
				Db::rollback();
				return json(["code"=>400,'msg'=>'系统繁忙请稍后再试!']);
			}
		}else{
			Db::rollback();
			return json(["code"=>400,'msg'=>'系统繁忙请稍后再试!!']);
		}
	}
	//发送模板消息给用户和商家
	function set_temp($user,$balance,$origin_price,$score,$sn,$agent_info,$chain_id){
		//发送用户付款通知
			if($user&&$user['openid']){
				$remark="付款成功";
				if($score<0){
					$remark.=",鼓励金账号增加".sprintf("%.2f",$score);
				}elseif($score>0){
					$remark.=",使用鼓励金抵扣".sprintf("%.2f",$score);
				}
				$data=array(
			 	"first" => array(
	                "value"=>'付款成功通知',
	            	"color"=>"#173177"
	            ),
	            "keyword1"=>array(
	               	"value"=>sprintf("%.2f",$balance),
	               	"color"=>"#173177"
				   ),
				"keyword2"=>array(
					"value"=>$agent_info['agent_name'],
					"color"=>"#173177"
				),
				"keyword3"=> array(
					"value"=>$sn,
	                "color"=>"#173177"                
				),
	            "keyword4"=> array(
	                "value"=>date('Y-m-d H:i:s'),
	                "color"=>"#173177"
	            ),
	            "remark"=> array(
	                "value"=>$remark,
	                "color"=>"#173177"
	            ),
			 );
	    	sendMessage($user['openid'],config("tempids.fk"),$data,config("WEB_DOMAIN")."index/member/index.html");	
			}
			//发送商户收款通知
			if($agent_info){
				$agent_user=db('info_user')->find($agent_info['user_id']);
				if(!$agent_user['openid']){
					return;
				}
				$remark="收款成功通知";
				if($score>0){
					$remark.=",用户抵扣回收鼓励金".$score;
				}elseif($paylog_info["agent_score"]<0){
					$remark.=",用户付款增送鼓励金".$score;
				}
				$chain_name=$agent_info['agent_name'];
				if($chain_id){
					$chain=db('agent_store')->field("store_name")->where("id",$chain_id)->find();
					$chain_name=$chain['store_name'];
				}
				$data=array(
			 	"first" => array(
	                "value"=>'用户付款通知',
	            	"color"=>"#173177"
	            ),
	            "keyword1"=>array(
	               	"value"=>$chain_name,
	               	"color"=>"#173177"
				   ),
	            "keyword2"=>array(
	               	"value"=>sprintf("%.2f",$balance),
	               	"color"=>"#173177"
				   ),
				"keyword3"=>array(
					"value"=>$origin_price,
					"color"=>"#173177"
				),
				"keyword4"=> array(
					"value"=>date('Y-m-d H:i:s'),
	                "color"=>"#173177"                
				),
	            "keyword5"=> array(
	                "value"=>$sn,
	                "color"=>"#173177"
	            ),
	            "remark"=> array(
	                "value"=>$remark,
	                "color"=>"#173177"
	            ),
			 );
	    	sendMessage($agent_user['openid'],config("tempids.sk"),$data);	
			}
	}
		//添加日志
	function add_log1($agent_score,$user_id,$order_id,$agent_id,$chain_id,$emp_id,$sn,$pay_type,$state,$total_price,
	$pay_price,$oem_id,$sy_type=1,$house_id=0){
		$log=db("log_paylog")->where('order_sn',$sn)->field("id")->find();
		$data['agent_score']=$agent_score;
		$data['member_score']=-($agent_score);
		$data['uid']=$user_id;
		$data['state']=$state;
		$data['order_id']=$order_id;
		$data['agent_id']=$agent_id;
		$data['chain_id']=$chain_id;
		$data['clerk_id']=$emp_id;
		$data['order_type']=6;
		$data['order_sn']=$sn;
		$data['pay_type']=$pay_type;
		$data['origin_price']=$total_price;
		$data['balance']=$pay_price;
		$data['oem_id']=$oem_id;
		$data['add_time']=now_time();
		$data['sy_type']=$sy_type;
		$data['order_id']=$order_id;
		$data['house_id']=$house_id;
		if($log){
			$data['pay_time']=now_time();
			$res=db('log_paylog')->where('order_sn',$sn)->update($data);
		}else{
			$res=db('log_paylog')->insert($data);
		}
		return $res;
	}
	
}
